﻿using ArtClub.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ArtClub.DAL
{
    internal class MemberDB : IMemberDB
    {
        private ArtClubContext db = new ArtClubContext();

        public List<Member> ListMembers()
        {
            return (from m in db.Members
                    select m).ToList();
        }

        public List<Member> ListMembersByName(string name)
        {
            return (from m in db.Members
                    where m.Name.ToLower().Contains(name.ToLower())
                    select m).ToList();
        }

        public List<Member> ListMembersByEmail(string email)
        {
            return (from m in db.Members
                    where m.Email.ToLower().Contains(email.ToLower())
                    select m).ToList();
        }

        public List<Member> ListMembersByPoints(int minPoints)
        {
            return (from m in db.Members
                    where m.Points >= minPoints
                    select m).ToList();
        }

        public Member GetMember(int id)
        {
            return (from m in db.Members
                    where m.Id == id
                    select m).SingleOrDefault();
        }

        public void AddPoints(Model.Member member, int points)
        {
            // Get the member by id.
            var q = from m in db.Members
                    where m.Id == member.Id
                    select m;
            member = q.Single();

            // Add the points.
            member.Points += points;

            // Save
            db.SaveChanges();
        }

        public void RemovePoints(Model.Member member, int points)
        {
            // Get the member by id.
            var q = from m in db.Members
                    where m.Id == member.Id
                    select m;
            member = q.Single();

            // Remove the points.
            member.Points -= points;

            // Save
            db.SaveChanges();
        }

        public void CreateMember(Member member)
        {
            //Add the member
            db.Members.Add(member);

            //Save
            db.SaveChanges();
        }

		public void UpdateMember(Member member)
		{
			// Attach the updated member to the database.
			db.Members.Attach(member);
			// Tell EF that the member is an update.
			db.Entry(member).State = System.Data.Entity.EntityState.Modified;
			// Save changes.
			db.SaveChanges();
		}
		public void DeleteMember(int id)
		{
			// Remove the member
			db.Members.Remove(GetMember(id));

			//Save
			db.SaveChanges();
		}
	}
}